package com.cloud.code.socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {

    private static Scanner scanner = new Scanner(System.in);

    private static ObjectOutputStream objectOutputStream;
    private static ObjectInputStream objectInputStream;

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        try {
            Socket socket = new Socket("localhost", 6666);
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            System.out.println("你的名字：");
            String name = scanner.nextLine();
            Message message = new Message();
            message.setFromUser(name);
            message.setMsgType(MsgType.LGOIN);
            objectOutputStream.writeObject(message);

            Message mes = (Message) objectInputStream.readObject();
            System.out.println("msg:" + mes.getMsg());

            executorService.execute(new UserReader(objectInputStream));

            Boolean flag = true;
            while (flag) {
                System.out.println("接收人姓名：");
                String toUser = scanner.nextLine();
                Message message1 = new Message();
                message1.setToUser(toUser);
                System.out.println("说什么：");
                String msg = scanner.nextLine();
                message1.setMsgType(MsgType.SEND);
                message1.setFromUser(name);
                message1.setMsg(msg);
                objectOutputStream.writeObject(message1);
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

class UserReader implements Runnable {

    private ObjectInputStream objectInputStream;

    public UserReader(ObjectInputStream objectInputStream) {
        this.objectInputStream = objectInputStream;
    }

    @Override
    public void run() {
        Boolean flag = true;
        while (flag) {
            try {
                Message message = (Message) objectInputStream.readObject();
                System.out.println(message.getFromUser() + "对你说：" + message.getMsg());
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}
